package com.jd.basic.service.impl;

import com.jd.basic.config.BussinessException;
import com.jd.basic.eum.UserRegisterConstant;
import com.jd.basic.service.VerifyCodeService;
import com.jd.basic.util.*;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.dto.EmailRegisterDto;
import com.jd.user.dto.PhoneRegisterDto;
import com.jd.user.dto.SendEmailCodeDto;
import com.jd.user.dto.SendMobileCodeDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements VerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void sendPhone(SendMobileCodeDto sendMobileCodeDto) {
        System.err.println("绑定账号业务层" + sendMobileCodeDto);
        if (sendMobileCodeDto.getType().equals("binder")){
            sendMobileCode(sendMobileCodeDto,UserRegisterConstant.BINDER_CODE_KEY);
        }else if (sendMobileCodeDto.getType().equals("register")){
            verifyImageCode(sendMobileCodeDto);
            sendMobileCode(sendMobileCodeDto,UserRegisterConstant.PHONE_CODE_KEY);
        }
    }

    @Override
    public synchronized String imageCode(String imageCode) throws IOException {
        System.err.println("获取" + imageCode);
        // 获取验证码
        String code = VerifyCodeUtils.generateVerifyCode(1);
        System.err.println("获取的四位验证码" + code);
        // 存入redis
        redisTemplate.opsForValue().set(imageCode,code,3, TimeUnit.MINUTES);
        // 3.返回base64编码的
        return VerifyCodeUtils.VerifyCode(80,30,code);
    }

    private void sendMobileCode(SendMobileCodeDto sendMobileCodeDto,String phoneCode) {
        // 判断手机号是否合法
        VerifyPhone(sendMobileCodeDto);
        // 判断是否60s内重复发送
        Long timeout = redisTemplate.getExpire(String.format(phoneCode
                                              ,sendMobileCodeDto.getPhone()));
        if (timeout>(UserRegisterConstant.PHONE_CODE_TIME-1*60L)){
            throw  new BussinessException("60S内请勿重复点击");
        }
        // 如果redis里还有老的验证码 就不发送新的了
        String  oldPhoneCode = (String)redisTemplate.opsForValue()
                .get(String.format(phoneCode,sendMobileCodeDto.getPhone()));
        System.err.println("old验证码"  + oldPhoneCode);
        if (StringUtils.isBlank(oldPhoneCode)){
            // 如果为空 就重新生成一个四位数的短信验证码
            oldPhoneCode = StrUtils.getRandomString(4);
        }
        log.info("手机验证码：{}",oldPhoneCode);
        // 存入redis
        redisTemplate
                .opsForValue()
                .set(String.format(phoneCode,sendMobileCodeDto.getPhone())
                        ,oldPhoneCode
                        ,5
                        ,TimeUnit.MINUTES);
        try {
            SmsUtil.send(oldPhoneCode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Override
    public void sendEmailCode(SendEmailCodeDto sendEmailCodeDto) {
        // 判断是否60s内重复发送
        Long timeout = redisTemplate.getExpire(String.format(UserRegisterConstant.EMAIL_CODE_KEY
                ,sendEmailCodeDto.getEmail()));

        if (timeout>(UserRegisterConstant.EMAIL_CODE_TIME-1*60L)){
            throw  new BussinessException("60S内请勿重复点击");
        }
        // 如果redis里还有老的验证码 就不发送新的了
        String  oldEmailCode = (String)redisTemplate.opsForValue()
                .get(String.format(UserRegisterConstant.EMAIL_CODE_KEY,sendEmailCodeDto.getEmail()));
        System.err.println("old验证码"  + oldEmailCode);
        if (StringUtils.isBlank(oldEmailCode)){
            // 如果为空 就重新生成一个四位数的短信验证码
            oldEmailCode = StrUtils.getRandomString(4);
        }
        log.info("邮箱验证码验证码：{}",oldEmailCode);
        // 存入redis
        redisTemplate
                .opsForValue()
                .set(String.format(UserRegisterConstant.EMAIL_CODE_KEY,sendEmailCodeDto.getEmail())
                        ,oldEmailCode
                        ,5
                        ,TimeUnit.MINUTES);

        // 调用工具类发送邮件
        SendEmailUtil.sendEmail(oldEmailCode,sendEmailCodeDto.getEmail(),javaMailSender);
    }

    @Override
    public void phoneRegister(PhoneRegisterDto phoneRegisterDto) {
        // 判断手机号是否合法
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$"); // 验证手机号
        Matcher matcher = pattern.matcher(phoneRegisterDto.getPhone());
        if (!matcher.matches()){
            throw new BusinessException("手机号格式不正确！");
        }
        // 判断手机号是否已经注册过了
        User user = userMapper.findByPhone(phoneRegisterDto.getPhone());
        if (null!=user){
            throw new BussinessException("该手机号已经注册过了");
        }
        // 验证两次密码是否一致
        if (!phoneRegisterDto.getPassword().equals(phoneRegisterDto.getConfirmPassword())){
            throw new BusinessException("两次密码不一致！");
        }
        // 验证手机号验证码是否正确
        String redisPhoneCode = (String) redisTemplate.opsForValue().get(String.format(UserRegisterConstant.PHONE_CODE_KEY,phoneRegisterDto.getPhone()));
        System.err.println("redis中的code" + redisPhoneCode);
        if (StringUtils.isBlank(redisPhoneCode) || !redisPhoneCode.equals(phoneRegisterDto.getPhoneCode())){
            throw new BusinessException("手机验证码错误！");
        }
        // 保存数据 先 logininfo 再user
        user = phoneRegisterDto.getUser();
        // 构建logininfo对象
        Logininfo logininfo = new Logininfo();
        // 这个api 会将user对象中的字段值 复制到logininfo中 前提是两个实体字段相同
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(true);
        logininfo.setType(1);
        // 添加logininfo表
        System.err.println("Logininfo添加测试" + logininfo);
        logininfoMapper.add(logininfo);
        // 在添加user表 将logininfoid set到user表中
        user.setLogininfoId(logininfo.getId());
        System.err.println("手机添加测试" + user);
        userMapper.add(user);

    }

    @Override
    public void emailRegister(EmailRegisterDto emailRegisterDto) {
        // 参数校验
        if (!emailRegisterDto.getPassword().equals(emailRegisterDto.getConfirmPassword())){
            throw new BusinessException("两次密码不一致！");
        }
        // 验证手机号验证码是否正确
        String redisPhoneCode = (String) redisTemplate.opsForValue().get(String.format(UserRegisterConstant.EMAIL_CODE_KEY,emailRegisterDto.getEmail()));
        System.err.println("redis中的code" + redisPhoneCode);
        if (StringUtils.isBlank(redisPhoneCode) || !redisPhoneCode.equals(emailRegisterDto.getEmailCode())){
            throw new BusinessException("手机验证码错误！");
        }
        User user = emailRegisterDto.getUser();
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(true);
        logininfo.setType(1);
        // 添加logininfo表
        System.err.println("Logininfo添加测试" + logininfo);
        logininfoMapper.add(logininfo);
        // 在添加user表 将logininfoid set到user表中
        user.setLogininfoId(logininfo.getId());
        System.err.println("手机添加测试" + user);
        userMapper.add(user);

    }



    @Override
    public void sendEmail(SendEmailCodeDto sendEmailCodeDto) {
        String redisImageCode = (String) redisTemplate.opsForValue().get(sendEmailCodeDto.getImageCodeKey());
        if (StringUtils.isBlank(redisImageCode) || !redisImageCode.equalsIgnoreCase(sendEmailCodeDto.getImageCodeValue())) {
            throw new BusinessException("图形验证码错误！");
        }
    }


    private void VerifyPhone(SendMobileCodeDto sendMobileCodeDto) {
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$"); // 验证手机号
        Matcher matcher = pattern.matcher(sendMobileCodeDto.getPhone());
        if (!matcher.matches()){
            throw new BusinessException("手机号格式不正确！");
        }
        // 判断手机号是否已经注册过了
        User user = userMapper.findByPhone(sendMobileCodeDto.getPhone());
        if (sendMobileCodeDto.getType().equals("binder")){

        }else if (sendMobileCodeDto.getType().equals("register") && user!=null){
            throw new BussinessException("该手机号已经注册过了");
        }
    }

    private void verifyImageCode(SendMobileCodeDto dto) {
        // 1.参数验证
        if (StringUtils.isBlank(dto.getImageCodeKey())){
            throw new BussinessException("请输入图形验证码");
        }
        //2.图形验证码是否正确
        // 从redis中获取到图形验证码 然后和dto中的图形验证码进行比较
        String redisImageCode = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (StringUtils.isBlank(redisImageCode) || !redisImageCode.equalsIgnoreCase(dto.getImageCodeValue())) {
            throw new BusinessException("图形验证码错误！");
        }
        // 3.手机号是否注册过
        // 根据dto中的手机号查询user表中是否有数据
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user) {
            throw new BusinessException("滚去登陆！");
        }
    }
}
